package com.dehui.traders.service;

import android.util.Log;

import com.dehui.traders.BuildConfig;
import com.dehui.traders.app.AppApplication;
import com.dehui.traders.config.Preferences;
import com.dehui.traders.service.request.HeaderRequest;
import com.dehui.traders.utils.Utils;
import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by hqq on 18.5.7.
 */

public class RetrofitHelper {

    public static final String BASE_URL = BuildConfig.BASEURL;
    //    public static final String TEST_URL = "http://192.168.3.17:8090/";

    public static API getAPI(){

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(getOkHttpClient())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        return retrofit.create(API.class);
    }

    public static OkHttpClient getOkHttpClient(){
        OkHttpClient.Builder client = new OkHttpClient.Builder();
        client.addInterceptor(headInterceptor);
        client.addInterceptor(loggingInterceptor);
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient httpClient = client.build();
        return httpClient;
    }

    static Interceptor headInterceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {

            String token = Preferences.getToken();
            String phone = Preferences.getPhone();
            String userId = Preferences.getUserId();
            HeaderRequest headerRequest = new HeaderRequest(phone,String.valueOf(AppApplication.getVersionCode()),
                    userId,"android", Utils.getSystemVersion(),"",Utils.getDeviceBrand() + Utils.getSystemModel(),
                    AppApplication.getVersionName(),token,Utils.getIPAddress(AppApplication.getContext()));

            Request original = chain.request();
            Request request = original.newBuilder()
                    .addHeader("Content-Type", "application/json")
                    .addHeader("headParam", new Gson().toJson(headerRequest))
                    .method(original.method(), original.body())
                    .build();

            return chain.proceed(request);
        }
    };

    static HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
        @Override
        public void log(String message) {
            Log.i("retrofitBack",message);
        }
    });




}
